<template>
	<view class="app-system-pay-nearby-goods-info e-rela">
		<view class="e-rela e-m-b-20">
			<!-- #ifndef APP-PLUS -->
			<view class="app-system-pay-nearby-goods-info__swiper">
				<e-swiper
					:list="swiperList"
					imgMode="heightFix"
					height="750rpx"
					@click="previewImage"
					@change="swiperChange"
					circular
					keyName="url"
					radius="0"
					:autoplay="false"
					v-if="swiperList.length"
				>
					<template #indicator>
						<view class="indicators e-flex">
							<view class="indicators-item e-m-r-4" :class="{ 'indicators-active': index === current }" v-for="(item, index) in swiperList" :key="index"></view>
						</view>
					</template>
				</e-swiper>
			</view>

			<!-- #endif  -->
			<!-- #ifdef APP-PLUS -->
			<view class="app-system-pay-nearby-goods-info__swiper-box bg-white">
				<swiper class="app-system-pay-nearby-goods-info__swiper" :current="current" circular @change="swiperChange">
					<swiper-item class="app-system-pay-nearby-goods-info__swiper-img e-rela" :item-id="videoUrl" v-if="videoUrl">
						<view class="app-system-pay-nearby-goods-info__swiper-video app-system-pay-nearby-goods-info__swiper-img">
							<template v-if="osName === 'android'">
								<video
									id="goodsVideo"
									ref="goodsVideo"
									class="e-abso"
									:src="videoUrl"
									:controls="videoControls"
									:enable-play-gesture="false"
									autoplay
									@play="playVideo"
									@pause="endVideo"
									@ended="endVideo"
									v-show="videoControls"
								></video>
							</template>
							<template v-else>
								<video
									id="goodsVideo"
									ref="goodsVideo"
									class="e-abso"
									:src="videoUrl"
									:controls="videoControls"
									:enable-play-gesture="false"
									:initial-time="videoInitialTime"
									autoplay
									@timeupdate="videoTimeupdate"
									@play="playVideo"
									@pause="endVideo"
									@ended="endVideo"
									v-if="videoControls"
								></video>
							</template>

							<view class="app-system-pay-nearby-goods-info__swiper-video__mask e-abso e-flex-xy-center" v-show="!videoControls" @tap="plays">
								<image src="/static/app/play.png"></image>
							</view>
						</view>
					</swiper-item>
					<block v-for="(item, index) in imageList" :key="index">
						<swiper-item :item-id="`${index}`">
							<view class="app-system-pay-nearby-goods-info__swiper-img">
								<load-image mode="heightFix" size="100vw" :src="item" @tap="previewImage(index)"></load-image>
							</view>
						</swiper-item>
					</block>
				</swiper>
				<view class="indicators e-abso e-flex">
					<view class="indicators-item e-m-r-4" :class="{ 'indicators-active': index === current }" v-for="(item, index) in swiperList" :key="index"></view>
				</view>
			</view>
			<!-- #endif  -->
		</view>
		<view class="e-p-l-20 e-p-r-20">
			<view class="bg-white e-p-t-20 e-p-l-30 e-p-r-30 e-p-b-30 e-radius-20">
				<view class="e-m-b-30 e-flex e-flex-between">
					<view>
						<text class="c-red e-font-48 e-m-r-20">{{ $unitEn }}{{ info.price || 0 }}</text>
					</view>
					<image class="share-icon" :src="$staticPath('layout/basics/share1.png')" @tap="share" />
				</view>
				<view class="e-font-32 fw-500 e-m-b-20">
					{{ info.name }}
				</view>
				<view class="e-flex e-flex-between">
					<!-- <view class="c-secondary e-font-24">
						<text class="e-p-r-10">{{ $t('common.销量') }}</text>
						<text>{{ $formatNumberToK(info.stockSold || 0) }}</text>
					</view> -->
					<view class="e-font-24" style="color: #b1b1b3" v-if="info.collectCount">{{ info.collectCount }}{{ $t('nearby.人喜欢') }}</view>
				</view>
			</view>
		</view>
		<!-- #ifndef MP-WEIXIN ||MP-ALIPAY-->
		<share-popup type="1" :shareUrl="webShareUrl" :mpShareUrl="mpShareUrl" :show="sharePopupShow" @close="sharePopupShow = false"></share-popup>
		<!-- #endif -->
		<view class="canvas-box e-abso">
			<canvas ref="canvas" class="goodsInfo-canvas" id="goodsInfo-canvas" canvas-id="goodsInfo-canvas"></canvas>
		</view>
	</view>
</template>

<script lang="ts">
export default {
	// #ifdef MP-WEIXIN
	// 将自定义节点设置成虚拟的，更加接近Vue组件的表现，能更好的使用e-flex属性
	options: {
		virtualHost: true
	}
	// #endif
};
</script>
<script lang="ts" setup>
import { ref, computed,watch } from 'vue';
import { useCurrentInstance, useCanvas } from '@/common/hooks';
import { drawQRCode, drawRoundedRectangle, drawText, getTextLineHeight } from '@/common/canvas';
/* 引入uqrcode核心js */
import { uQRCode, os, getAppImageInfo } from '@/common/utils'
import { getGoodsShareUrl } from '@/common/request/api';
import type { StoreGoodsDetail } from '@/common/request/api';
import { useUser } from '@/common/stores';
import { storeToRefs } from 'pinia';
import type { UniGlobalData } from '@/typings/uni';
import type { RequestFromType } from '@/common/request/type';

const props = defineProps<{
	info: StoreGoodsDetail;
	goodsId: string;
	videoStop: boolean;
}>();
const emit = defineEmits(['setVideoStop']);

const ctx = useCurrentInstance();

const { isLogin } = storeToRefs(useUser());

const webShareUrl = ref('');
const { canvasdraw, canvasImgUrl: mpShareUrl } = useCanvas();

const sharePopupShow = ref(false);

const osName = os();
const videoControls = ref(true);
const videoInitialTime = ref(1);
let videoContext: ReturnType<typeof uni.createVideoContext> | null = null;
watch(
	() => props.videoStop,
	(newValue) => {
		if (!videoContext) {
			videoContext = uni.createVideoContext('goodsVideo');
		}
		if (newValue) {
			videoContext.pause();
			videoControls.value = false;
			emit('setVideoStop');
		}
	}
);

const videoTimeupdate = (e: { detail: { currentTime: number } }) => {
	if (osName === 'ios') {
		videoInitialTime.value = e.detail.currentTime;
	}
};
const plays = () => {
	videoControls.value = true;

	if (!videoContext) {
		videoContext = uni.createVideoContext('goodsVideo');
	}
	videoContext.play();
};
const playVideo = () => {
	// this.videoMaskShow = false
};
const endVideo = () => {
	videoControls.value = false;
};

const current = ref(0);
const swiperChange = (e: { current: number; detail: { current: number } }) => {
	let _current = 0;
	// #ifdef APP-PLUS
	_current = e.detail.current;
	if (videoContext !== null) {
		setTimeout(() => {
			if (_current !== 0) {
				videoContext?.pause();
			}
		}, 400);
	}

	// #endif
	// #ifndef APP-PLUS
	_current = e.current;
	// #endif
	current.value = _current;
};

const imageList = computed(() => {
	return props.info?.description?.imgUrls?.split(',') || [];
});
const videoUrl = computed(() => {
	return props.info?.description?.videoUrl ? ctx.$fullLink(props.info?.description?.videoUrl) :'' ;
});

const previewList = computed(() => {
	return imageList.value.map((item) => ctx.$fullLink(item));
});

const swiperList = computed(() => {
	let arr = [];
	if (videoUrl.value) {
		arr.push({
			url: videoUrl.value,
			type: 'video'
		});
	}
	if (previewList.value) {
		return [
			...arr,
			...previewList.value.map((item) => {
				return {
					url: item,
					type: 'image'
				};
			})
		];
	}
	return arr;
});

const previewImage = (current: number) => {
	uni.previewImage({
		current,
		urls: previewList.value
	});
};

const draw = async (shareUrl: string) => {
	let goodsImgUrl = ctx.$fullLink(imageList.value[0]);
	canvasdraw({
		bgImgUrl: goodsImgUrl,
		canvasId: 'goodsInfo-canvas',
		that: ctx,
		width: 290,
		height: 390,
		bgWidth: 290,
		bgHeight: 290,
		drawIng: async (canvasCtx) => {
			let { name = '', price } = props.info;
			const $unitEn = ctx.$unitEn;
			drawText(canvasCtx, {
				x: 20,
				y: 320,
				text: $unitEn,
				size: 10,
				fillStyle: '#F5222D',
				font: 'normal normal bold 10px'
			});

			drawText(canvasCtx, {
				x: 22 + canvasCtx.measureText($unitEn).width,
				y: 320,
				text: price,
				size: 22,
				fillStyle: '#F5222D',
				font: 'normal normal bold 22px'
			});
			canvasCtx.setFontSize(14);
			let { row: textList } = getTextLineHeight(canvasCtx, {
				w: 120,
				text: name
			});

			drawText(canvasCtx, {
				x: 20,
				y: 348,
				text: textList[0],
				size: 14,
				fillStyle: '#333',
				font: 'normal normal bold 14px'
			});
			if (textList.length > 2) {
				textList[1] = textList[1].substr(0, textList[1].length - 2) + '...';
			}
			textList[1] &&
				drawText(canvasCtx, {
					x: 20,
					y: 368,
					text: textList[1],
					size: 14,
					fillStyle: '#333',
					font: 'normal normal bold 14px'
				});
			// #ifdef MP-WEIXIN||MP-ALIPAY

			let codePath = await getAppImageInfo(ctx.$fullLink(shareUrl));
			if (codePath.path) {
				canvasCtx.drawImage(codePath.path, 208, 310, 65, 65);
			}
			// #endif
			// #ifndef MP-WEIXIN||MP-ALIPAY
			const logo = uni.getStorageSync('logo');
			if (logo) {
				const logoResult = await getAppImageInfo(ctx.$fullLink(logo));
				// 等比例缩放
				const logoW = logoResult.width;
				const logoH = logoResult.height;
				const _lw = 45;
				const _lh = parseInt(`${(_lw * logoH) / logoW}`);
				if (logoResult.path) {
					canvasCtx.drawImage(logoResult.path, 228, 20, _lw, _lh);
				}
			}
			drawRoundedRectangle(canvasCtx, {
				x: 208,
				y: 310,
				width: 65,
				height: 65,
				radius: 0,
				lineWidth: 2,
				strokeStyle: '#E7E7E7'
			});
			drawQRCode(canvasCtx, {
				x: 213,
				y: 315,
				size: 55, //二维码大小
				margin: 0, // 填充边距
				modules: uQRCode.getModules({
					id: 'goodsInfo-canvas', //canvasId
					mode: 'canvas', // 生成模式
					size: 180, //二维码大小
					margin: 0, // 填充边距
					backgroundColor: '#fff', // 背景色
					foregroundColor: '#000', // 前景色
					errorCorrectLevel: uQRCode.errorCorrectLevel.H, // 纠错等级
					text: shareUrl
				})
			});
			webShareUrl.value = shareUrl;
			// #endif
		}
	})
		.then(() => {
			showShare();
		})
		.finally(() => {
			uni.hideLoading();
		});
};

const share = () => {
	if (isLogin.value) {
		uni.showLoading({
			title: 'loading...'
		});
		// 如果是小程序，获取的是分享卡片上的二维码地址
		// h5获取的是分享的当前页面地址
		let url = 'pages/systemPay/nearby/goods/index';
		// #ifndef MP-WEIXIN||MP-ALIPAY
		url = '/' + url;
		// #endif
		let formType: RequestFromType = 'mp_private';

		// #ifndef  PRIVATE
		formType = getApp<UniGlobalData>().globalData?.payFromType;
		// #endif
		getGoodsShareUrl({
			url,
			formType,
			scene: ctx.$getShareUrlScene(`id=${props.goodsId}`)
		})
			.then((res) => {
				draw(res.shareUrl);
			})
			.catch(() => {
				uni.hideLoading();
			});
	} else {
		ctx.$goLogin({
			isShowModal: false
		});
	}
};
const showShare = () => {
	// #ifdef MP-WEIXIN
	wx.showShareImageMenu({
		path: mpShareUrl.value
	});
	// #endif
	// #ifndef MP-WEIXIN
	sharePopupShow.value = true;
	// #endif
};
</script>

<style lang="scss" scoped>
@include appBem_b(system-pay-nearby-goods-info) {
	@include appBem_e(swiper-img) {
		width: 100vw;
		height: 750rpx;
	}
	@include appBem_e(swiper-box) {
		width: 100vw;
	}
	@include appBem_e(swiper) {
		white-space: nowrap;
		height: 750rpx;

		&-video {
			video {
				left: 0;
				right: 0;
				bottom: 0;
				top: 0;
				width: 100%;
				height: 750rpx;
			}

			&__mask {
				left: 0;
				right: 0;
				bottom: 0;
				top: 0;
				width: 100%;
				height: 750rpx;
				background-color: #000;

				image {
					width: 120rpx;
					height: 120rpx;
				}
			}
		}
	}
	.indicators {
		left: 358rpx;
		top: 702rpx;
		z-index: $z-index-normal;

		.indicators-item {
			width: 8rpx;
			height: 8rpx;
			border-radius: 50%;
			background: #c6ccd7;
		}

		.indicators-active {
			width: 32rpx;
			border-radius: 4rpx;
			background-color: #989fad;
		}
	}

	.share-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.canvas-box {
		left: -9999px;
		top: -9999px;

		.goodsInfo-canvas {
			width: 290px;
			height: 390px;
			font-kerning: normal;
		}
	}
}
</style>
